package mspbots.data.manage.config;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.reactive.config.WebFluxConfigurer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * data.connector.web.config.WebConfiguration
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/4/3
 */
@Configuration
@EnableScheduling
public class AppConfiguration implements WebFluxConfigurer {

    @Value("${spring.jackson.date-format}")
    private String localDateTimePattern;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer dataTimeJacksonMapperCustomizer() {
        return builder -> builder.serializersByType(Map.of(
                LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(localDateTimePattern))
                , LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE)));
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToLocalDateTimeConverter());
        registry.addConverter(new StringToLocalDateConverter());
    }

    /**
     * com.mspbots.sync.config.StringToLocalDateTimeConvert
     *
     * @author Alex bob(https://github.com/vnobo)
     * @date Created by 2019/6/26
     */
    static class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {

        @Override
        public LocalDateTime convert(String source) {
            return LocalDateTime.parse(source, DateTimeFormatter.ISO_DATE_TIME);
        }
    }

    /**
     * com.mspbots.core.config.StringToLocalDateConverter
     *
     * @author Alex bob(https://github.com/vnobo)
     * @date Created by 2019/8/29
     */
    static class StringToLocalDateConverter implements Converter<String, LocalDate> {

        @Override
        public LocalDate convert(String source) {
            return LocalDate.parse(source, DateTimeFormatter.ISO_LOCAL_DATE);
        }
    }

}
